<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/8/9
 * Time: 5:52 PM
 */

namespace app\aliyun\controller;

use AlibabaCloud\SDK\Dyvmsapi\V20170525\Dyvmsapi;
use AlibabaCloud\SDK\Dyvmsapi\V20170525\Models\SingleCallByTtsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use think\Log;

class AliyunPhone
{

    protected static $accessKeyId = 'LTAI5tD1JsPDMfHn88z3sw6Z';
    protected static $accessSecret = '6JoGLaug4cJu6xdfOydWsOEzZSOQqM';

    /**
     * 使用AK&SK初始化账号Client
     * @return Dyvmsapi Client
     */
    private static function createClient()
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => self::$accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => self::$accessSecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dyvmsapi
        $config->endpoint = "dyvmsapi.aliyuncs.com";
        return new Dyvmsapi($config);
    }

    /**
     * 向指定号码发送语音验证码或文本转语音类型的语音通知
     * 对同一个“资质+用途”下的主叫进行流控限制：1次/分钟、5次/小时、20次/24小时（流控规则计时从第一次正常外呼开始）
     * @return void
     */
    public static function singleCallByTts($tel, $telCodeId)
    {
        $client = self::createClient();
        $singleCallByTtsRequest = new SingleCallByTtsRequest([
            "calledNumber" => $tel,
            "ttsCode" => $telCodeId,
            "playTimes" => 1,//一通电话内语音通知内容的播放次数。取值范围：1~3
            "volume" => 100,//语音通知的播放音量。取值范围：0~100，默认取值100。
        ]);
        $runtime = new RuntimeOptions([]);
        try
        {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->singleCallByTtsWithOptions($singleCallByTtsRequest, $runtime);
            $code = $res->body->code;
            $message = $res->body->message;
            if (strtoupper($code) !== 'OK')
            {
                Log::write("{$tel}阿里语音验证码{$telCodeId}通知异常:" . $message, 'error', true);
            }
        }
        catch (\Exception $error)
        {
            if (!($error instanceof TeaError))
            {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            Log::write("{$tel}阿里语音验证码{$telCodeId}通知异常:" . $error->message, 'error', true);
        }
    }
}
